package com.alpha.service.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

/**
 * SpringBoot 应用上下文
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Component
@SuppressWarnings("unused")
public class AlphaApplicationContext implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    private static ApplicationContext applicationContext;

    /**
     * 获取应用名称
     *
     * @return 应用名称
     */
    public static String getApplicationName() {
        return applicationContext.getEnvironment().getProperty("spring.application.name");
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    private static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    @Override
    public void initialize(@Nonnull ConfigurableApplicationContext applicationContext) {
        AlphaApplicationContext.setApplicationContext(applicationContext);
    }
}
